package org.jaaksi.customviewdemo.view

import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Canvas
import android.graphics.Rect
import android.util.AttributeSet
import android.view.animation.LinearInterpolator
import androidx.appcompat.widget.AppCompatImageView
import androidx.core.animation.doOnEnd
import androidx.core.graphics.withSave

// 让图片动画从左往右一点点展示出来
class AnimImageView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null
) : AppCompatImageView(context, attrs) {

    private var animFrame = Rect()
    private var anim: ValueAnimator? = null

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        animFrame.set(0, 0, 0, h)
    }

    // 在post方法中调用？
    fun startAnim(animDuration: Long = 1000L, onEnd: () -> Unit) {
        anim?.end()
        anim = null
        anim = ValueAnimator.ofInt(0, width).apply {
            duration = animDuration
            interpolator = LinearInterpolator()
            addUpdateListener {
                animFrame.right = it.animatedValue as Int
                postInvalidate()
            }
            doOnEnd { onEnd.invoke() }
            start()
        }
    }

    override fun onDraw(canvas: Canvas) {
        canvas.withSave {
            canvas.clipRect(animFrame)
            super.onDraw(canvas)
        }
    }

    fun destroy() {
        anim?.cancel()
    }
}